var webapi = "https://api-shake.xinglongdayuan.com";
var webApp = {};
var bridge;
var c_audio = document.getElementById('c_audio');
var c_audio2 = document.getElementById('c_audio2');
var c_audio3 = document.getElementById('c_audio3');
var timestamp = null;
var times;
var startTime = 1557902669; //起始时间
var interval = 60; //间隔时长，单位是分钟
var number = 100; //活动轮数
var intDiff = parseInt(59); //倒计时总秒数量
var intDiff1;
var sTimer = null;
var sTimer0 = null;
var Latitude; //地理位置--纬度
var Longitude; //地理位置--经度
c_audio3.load();
CYutils.loading();
var canplay = false;
var touchTriggerAudio = function () {
    c_audio.play();
    c_audio.pause();
    c_audio2.play();
    c_audio2.pause();
    c_audio3.play();
    c_audio3.pause();
    document.removeEventListener('touchstart', touchTriggerAudio)
}
document.addEventListener('touchstart', touchTriggerAudio, false);
// $(function () {
//     function snow(left, height, src) {
//         var div = document.createElement("div");
//         var img = document.createElement("img");
//         div.appendChild(img);
//         img.className = "roll";
//         img.src = src;
//         div.style.left = left + "px";
//         div.style.height = height + "px";
//         div.className = "div";
//         document.getElementById("snowzone").appendChild(div);
//         setTimeout(function () {
//             document.getElementById("snowzone").removeChild(div);// console.log(window.innerHeight);
//         }, 5000);
//     }

//     setInterval(function () {
//         var left = Math.random() * window.innerWidth;
//         var height = Math.random() * window.innerHeight;
//         var src = "./images/2019/彩票" + Math.floor(Math.random() * 6 + 1) + ".png";//两张图片分别为"s1.png"、"s2.png"
//         snow(left, height, src);
//     }, 200);
// });
var img = ['./images/yyy.png',
    './images/yzb.png',
    './images/shuoming.png',
    './images/wzbg.png',
    './images/hdxz.png',
    './images/yybg.jpg',
    './images/s1.png',
    './images/s2.png',
    './images/s3.png',
    './images/s4.png',
    './images/2019/彩票1.png',
    './images/2019/彩票2.png',
    './images/2019/彩票3.png',
    './images/2019/彩票4.png',
    './images/2019/彩票5.png',
    './images/2019/彩票6.png'
];

//获取code
if (!CYutils.cookie.get('newopenid')) {
    location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx951684d2fdf00899&redirect_uri=https://shake.xinglongdayuan.com/getcode.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect';

}

if (CYutils.isIOS()) {
    document.addEventListener('WebViewJavascriptBridgeReady', function (event) {
        bridge = event.bridge;
    }, false)
};

// CYutils.dialog('活动已结束，奖券已发到您的卡券包，点击确定立即查看', {
//     onConfirm: function () {
//         window.location.href = 'https://wx52b1c0d4c35f2531.webwx.xinglongdayuan.com/app/member/discountvoucher';
//     }
// });
var isok = [];
var imgs = [];
var timed = 0;
for (var i in img) {
    imgs[i] = new Image();
    imgs[i].src = img[i];
}
var iCount = setInterval(function () {
    show();
}, 300);

function simulateLoading(container, progress) {
    if (typeof container === 'number') {
        progress = container;
        container = 'body';
    }
    setTimeout(function () {
        progress += Math.random() * 20;
        mui(container).progressbar().setProgress(progress);
        if (progress < 100) {
            simulateLoading(container, progress);
        } else {
            mui(container).progressbar().hide();
        }
    }, Math.random() * 200 + 200);
}
document.getElementById('process').innerHTML = 0 + '%';

function show() {
    for (var i in imgs) {
        if (imgs[i].complete != true) return false;
        timed++;
        document.getElementById('process').innerHTML = timed + '%';
        var progressbar1 = mui('#demo1');
        mui(progressbar1).progressbar().setProgress(timed);
    }
    document.getElementById('process').innerHTML = 100 + '%';
    mui(progressbar1).progressbar().setProgress(100);
    setTimeout(showdata, 300)
    clearInterval(iCount);

    function showdata() {
        jQuery("#demo1").hide();
        jQuery('.mui_turn').show();
    }

}
webApp.sendRequest = webapi + "/ol/shake/shake_start/" + mid; //摇一摇后调的接口
webApp.shake_detail = webapi + "/ol/shake/shake_detail/" + mid; //判断登录
webApp.shake_member = webapi + "/ol/shake/getSharkUser/" + mid; //会员信息
webApp.shake_allLogData = webapi + "/ol/shake/allLogData/" + mid; //别人的中奖记录
webApp.shake_prizeList = webapi + "/ol/shake/cashPrizeList/" + mid; //自己的中奖记录
webApp.shake_requestAlipay = webapi + "/ol/shake/requestAlipay/" + mid; //提现
webApp.batch_hexiao = webapi + "/ol/coupon/coupon_verify_batch/" + this.mid; //批量核销
webApp.hexiao_detail = webapi + "/ol/shake/getVerifyCount/" + this.mid; //核销券明细
webApp.getTime = webapi + "/ol/shake/getTime/" + mid; //获取id
webApp.getcode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx951684d2fdf00899&redirect_uri=https://shake.xinglongdayuan.com/queenActivity.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
    mui('.mui-scroll-wrapper').scroll({
        deceleration: 0.0005
    });

//活动详细------------------
jQuery('#hdxz').bind('tap', function () {
    start = false;
    jQuery('#rules').show();
    jQuery('#mui-backdrop').show();
    jQuery('html').css('height', '100%');
    jQuery('#rulesClose').bind('tap', function () {
        jQuery('#rules').hide();
        jQuery('#mui-backdrop').hide();
        start = true;
    });
});
jQuery('#mui-backdrop').bind('tap', function () {

    if (distanceCanUseShake) {
        jQuery('#rules').hide();
        jQuery('#success').hide();
        jQuery('#winningRecord').hide();
        jQuery('#error4').hide();
        jQuery('#error3').hide();
        jQuery('#error').hide();
        jQuery('#error').hide();
        jQuery('#mui-backdrop').hide();
        start = true;
        shakeStart();
    }

});

//活动详细------------------


//请求------------------
webApp.post = function (url, parameter, callback) {
    parameter = mui.extend({}, parameter);
    $.ajax({
        tpl: $('<div id="loadingToast" style="opacity: 1; display: block;">' +
            '<div class="weui-mask_transparent"></div>' +
            '<div class="weui-toast">' +
            '<i class="weui-loading weui-icon_toast"></i>' +
            '<p class="weui-toast__content">数据加载中</p>' +
            '</div>' +
            '</div>'),
        beforeSend: function () {
            this.tpl.appendTo('body')
        },
        complete: function () {
            try {
                this.tpl.remove()
            } catch (f) {}
        },
        url: url,
        dataType: 'jsonp',
        data: parameter,
        jsonp: 'callback',
        success: function (data) {
            if (data) {
                if (data.Error == 0) {
                    callback(data);
                } else {
                    callback(data);
                }
            }
        },
        error: function () {
            jQuery('#mui-backdrop').show();
            jQuery('#error').show();
            jQuery('#error').children('img').bind('tap', function () {
                jQuery('#error').hide();
                jQuery('#mui-backdrop').hide();
                start = true;
            })
            jQuery('#jxyyy2').bind('tap', function () {
                jQuery('#success').hide();
                jQuery('#mui-backdrop').hide();
                shakeStart();
                jQuery('#error').hide();
                start = true;
            })
            jQuery('#error2close').bind('tap', function () {
                jQuery('#error').hide();
                jQuery('#mui-backdrop').hide();
                start = true;
            })
        }
    });
}





//请求------------------
var shuju = {
    id: ''
};
var get_shuju = {
    tableid: ''
}
var imageObj = new Array(); //new Image();
var thumbs = [];
var allcount = '';
var count = '';
var tickedList = [];
var showebtry = true;
// var allLists=[];
var ids = [];
var couponId = {
    id: "",
    coupon_id: ""
};
var allLists = [];
var canUseShake = false;
var distanceCanUseShake = true;
var otherCanUseShake = false;
var isApp = CYutils.cookie.get('BDed_third_party_wxweb') === 'app';
var requestCount; //提现的金额
jQuery('#zjjl').click(function () {
    ids = [];
    start = false;
    webApp.post(webApp.shake_prizeList, {}, function (data) {
        if (data.Error == 0) {
            tickedList = data.data;
            $("#tickedList").html('');
            for (var j = 0; j < tickedList.length; j++) {
                couponId = {
                    id: "",
                    coupon_id: ""
                };
                if (tickedList[j].is_verify == 1) {
                    // $("#tickedList").append('<div class="hx_big"  style=" margin-bottom: 8px; "><div class="timehead2">中奖时间:' + tickedList[j].inputtime + '</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="' + j + '"><div class="ticket-left—use"><div class="text"><div class="list2">' + tickedList[j].title + '</div><div style="font-size: 0.12rem;">现金红包</div></div><div class="list1">兑奖截止时间:2019.03.08 24:00</div></div><div class="ticket-right—use ticket-right" data-id="' + j + '"></div></div></div></div>')
                    $("#tickedList").append('<div class="hx_big" style=" margin-bottom: 8px; "><div class="timehead2">中奖时间:' + tickedList[j].inputtime + '</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="' + j + '"><div class="ticket-left—use"><div style="padding: 20px 0px 14px;"><div class="text"><div class="list2">' + tickedList[j].price + '元</div><div style="font-size: 0.12rem;">现金红包</div></div><div class="list1">兑奖截止时间:2019.03.08 24:00</div></div><div class="ticket-right—use ticket-right" data-id="' + j + '"></div></div></div></div></div>')
                } else {
                    // $("#tickedList").append('<div class="hx_big" style=" margin-bottom: 8px; "><div class="timehead">中奖时间:' + tickedList[j].inputtime + '</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="' + j + '"><div class="ticket-left—unuse"><div class="list2">' + tickedList[j].title + '</div><div class="list1">兑奖时间:2019年2月14日</div></div></div></div></div>')
                    $("#tickedList").append('<div class="hx_big" style=" margin-bottom: 8px; "><div class="timehead">中奖时间:' + tickedList[j].inputtime + '</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="' + j + '"><div class="ticket-left—unuse"><div class="text"><div class="list2">' + tickedList[j].price + '元</div><div style="font-size: 0.12rem;">现金红包</div></div><div class="list1">兑奖截止时间:2019.03.08 24:00</div></div></div></div></div>')
                    // allLists.push({id:tickedList[j].id, coupon_id:tickedList[j].coupon_id})
                }
            }
            $("#all-xz").text('账户余额：' + data.count + '元');
            requestCount = data.count;
            // $("#tickedList").append('<div class="hx_big" style=" margin-bottom: 8px; "><div class="timehead2">中奖时间:2018.03.08</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="1"><div class="ticket-left—use"><div style="padding: 20px 0px 14px;"><div class="text"><div class="list2">3元</div><div style="font-size: 0.12rem;">现金红包</div></div><div class="list1">兑奖截止时间:2019.03.08 24:00</div></div><div class="ticket-right—use ticket-right" data-id="0"></div></div></div></div></div>')
            // $("#tickedList").append('<div class="hx_big" style=" margin-bottom: 8px; "><div class="timehead">中奖时间:' + '2018.03.08' + '</div><div class="ticket-list-item"><div class="ticketOutlet" data-id="' + '1' + '"><div class="ticket-left—unuse"><div class="text"><div class="list2">3元</div><div style="font-size: 0.12rem;">现金红包</div></div><div class="list1">兑奖截止时间:2019年2月14日</div></div></div></div></div>')
            // allLists.push({id:tickedList[j].id, coupon_id:tickedList[j].coupon_id})

            // var tiptime = window.setTimeout(refreshCount(), 2000);

            // function refreshCount() {
            //     var hxNull = $("#tickedList .timehead");
            //     if (hxNull.length <= 0) {
            //         $(".product-all").addClass("allno");
            //         mui.toast("您目前可提现金额0");
            //     } else {
            //         $(".product-all").removeClass("allno");
            //     };
            // }
            //去掉定时器  
            // window.clearTimeout(tiptime);

            // jQuery(".timehead").click(function () {
            //     var _index = $(this).parent(".hx_big").index();
            //     var couponId = {
            //         id: "",
            //         coupon_id: ""
            //     };

            //     if ($(this).find(".product-em").is(".iptimg")) {
            //         console.log(_index);
            //         couponId.id = tickedList[_index].id;
            //         couponId.coupon_id = tickedList[_index].coupon_id;
            //         for (var a = 0; a < ids.length; a++) {
            //             if (couponId.id == ids[a].id) {
            //                 ids.splice(a, 1);
            //             }
            //             // console.log(ids);
            //         }
            //         console.log(ids);
            //         // console.log(allLists);

            //     } else {
            //         console.log(_index);
            //         couponId.id = tickedList[_index].id;
            //         couponId.coupon_id = tickedList[_index].coupon_id;
            //         ids.push({
            //             id: tickedList[_index].id,
            //             coupon_id: tickedList[_index].coupon_id
            //         });
            //         console.log(ids);
            //     }


            //     $(this).children(".product-em").toggleClass("iptimg");
            //     productxz();
            // });

            jQuery('#mui-backdrop').show();
            jQuery('#winningRecord').show();
            jQuery('#winningRecordClose').click(function () {
                jQuery(".product-sett").addClass("product-sett-a");
                jQuery(".product-all em").removeClass("product-all-on");
                jQuery(".product-all em").css("border", "1px solid #B8B4B4");
                jQuery('#mui-backdrop').hide();
                jQuery('#winningRecord').hide();
                start = true;
            });
        }

    });
});



//选中卡券
function productxz() {
    // console.log(222)
    var xz = $(".product-em");
    var xz1 = $(".iptimg");
    if (xz1.length == xz.length) {
        $(".product-all em").addClass("product-all-on");
        $(".product-all em").css("border", "0");
    } else {
        $(".product-all em").removeClass("product-all-on");
        $(".product-all em").css("border", "1px solid #B8B4B4");
    }
    if (xz1.length >= 1) {
        $(".product-sett").removeClass("product-sett-a");
    } else {
        $(".product-sett").addClass("product-sett-a");
    }
}
//全选卡券
jQuery(".product-all").click(function () {
    var fxk = $(".product-em");
    var qx = $(".product-all em");
    var jy = $(".product-sett");
    // console.log(111)
    $(".product-all").children("em").toggleClass("product-all-on");
    if ($(this).parent(".product-al").find(".product-all em").is(".product-all-on")) {
        webApp.post(webApp.shake_prizeList, {}, function (data) {
            if (data.Error == 0) {
                tickedList = data.data;
                for (var j = 0; j < tickedList.length; j++) {
                    if (tickedList[j].status != 2) {
                        allLists.push({
                            id: tickedList[j].id,
                            coupon_id: tickedList[j].coupon_id
                        })
                    }
                }
            }
        })
        ids = allLists;
        fxk.addClass("iptimg");
        $(".product-all em").css("border", "0");
        jy.removeClass("product-sett-a");
    } else {
        ids = [];
        fxk.removeClass("iptimg");
        $(".product-all em").css("border", "1px solid #B8B4B4");
        jy.addClass("product-sett-a");
    }
});
var clicktime = null
jQuery(".product-sett").click(function (event) {
    if (requestCount > 0.00) {
        $(".withdraw-auto p span").text(requestCount);
        $("input[name='input-account']").focus();
        $("input[name='input-account']").blur(function () {
            if ($("input[name='input-account']").val() == "" || $("input[name='input-name']").val() == "") {
                $("#ensure").addClass("product-sett-a")
            } else {
                $("#ensure").removeClass("product-sett-a");
            }
        })
        $("input[name='input-name']").blur(function () {
            if ($("input[name='input-account']").val() == "" || $("input[name='input-name']").val() == "") {
                $("#ensure").addClass("product-sett-a")
            } else {
                $("#ensure").removeClass("product-sett-a");
            }
        })
        // 全部提现----start

        jQuery('#winningRecord').hide();
        $("#error7").show();
        $("#ensure").on("click", function () {
            var _acount = $("input[name='input-account']").val();
            var _name = $("input[name='input-name']").val();
            $("input[name='input-account-t']").val(_acount);
            $("input[name='input-name-t']").val(_name);
            $("#error7").hide();
            $("#error8").show();
            $(".close-t").on("click", function () {
                $("input[name='input-account']").val("");
                $("input[name='input-name']").val("");
                $("input[name='input-account-t']").val("");
                $("input[name='input-name-t']").val("");
                $("#error8").hide();
                jQuery('#mui-backdrop').hide();
            })
            $("#t-back").on("click", function () {
                $("#error8").hide();
                $("#error7").show();
            })
            $("#t-submit").on("click", function () {
                var canclick = false;
                if (clicktime == null) {
                    canclick = true;
                    clicktime = timestamp;
                } else {
                    if (timestamp - clicktime > 60) {
                        canclick = true;
                        clicktime = timestamp;
                    } else {
                        canclick = false;
                        mui.toast('请勿频繁操作');
                    }
                }
                if (canclick) {
                    var userName = $("input[name='input-name-t']").val();
                    var userAccount = $("input[name='input-account-t']").val();
                    // ajax提现
                    $.ajax({
                        beforeSend: function () {
                            this.tpl.appendTo('body')
                        },
                        complete: function () {
                            try {
                                this.tpl.remove()
                            } catch (f) {}
                        },
                        url: webApp.shake_requestAlipay,
                        type: "POST",
                        dataType: 'json',
                        data: {
                            name: userName,
                            account: userAccount,
                            count: requestCount
                        },
                        success: function (data) {
                            if (data.Error == 0) {
                                mui.toast(data.Msg);
                            } else {
                                mui.toast(data.Msg);
                            }
                        },
                        error: function () {
                            mui.toast(data.Msg);
                        }
                    });

                    $("input[name='input-account']").val("");
                    $("input[name='input-name']").val("");
                    $("input[name='input-account-t']").val("");
                    $("input[name='input-name-t']").val("");
                    $("#error8").hide();
                    jQuery('#mui-backdrop').hide();
                }
                // location.reload();
            })
        });
        $(".close-q").on("click", function () {
            $("input[name='input-account']").val("");
            $("input[name='input-name']").val("");
            $("input[name='input-account-t']").val("");
            $("input[name='input-name-t']").val("");
            $("#error7").hide();
            jQuery('#mui-backdrop').hide();
        })
        event.stopPropagation();
        // 全部提现----end
    }
});

function shakeStart() {

    // ----------活动信息--------
    webApp.post(webApp.shake_detail, {}, function (data) {
        if (data.Error == 0) {
            canUseShake = true;
            shuju = data;
            shuju.id = data.data.id;
            // if(showebtry){
            //     $("#outletTitle").append('<div>' + data.enterprise.name + '</div>')
            //     showebtry = false;
            // }


            for (var i = 0; i < shuju['data']['prizeArr'].length; i++) {
                var keys = shuju['data']['prizeArr'][i]['prize_key']
                imageObj[keys] = new Image();
                // imageObj[keys].src = shuju['data']['prizeArr'][i]['thumb'];
            };
            // ----------会员信息-------------
            webApp.post(webApp.shake_member, {
                id: shuju.id
            }, function (data) {
                console.log(data)
                if (data.Error == 0) {
                    if (data.take == 0) {

                        // window.location.href = '/indexnewyear.html';
                    } else {
                        allcount = data.shake_num;
                        // document.getElementById('cjju').innerHTML = allcount;
                        jQuery('#cjju').html(allcount);
                    }

                } else if (data.data == '' || data.data.length < 1) {
                    mui.alert(data.Msg, '温馨提示', function () {
                        location.href = ' https://user.wx.xinglongdayuan.com/jumpurl?acurl=https://wx.shake.xinglongdayuan.com/yaoyiyao/queenActivity.html&comCode=1';
                    });
                } else {

                    mui.toast(data.Msg);
                }
            });
        } else if (data.Error == 6009) {
            // window.location.href = '/index.html';
            // window.location.href = '/indexnewyear.html';
        } else if (data.Error == 6007) {
            CYutils.dialog('请先登录', {
                onConfirm: function () {
                    if (CYutils.isWeiXin()) {
                        window.location.href = 'https://user.wx.xinglongdayuan.com/jumpurl?acurl=https://wx.shake.xinglongdayuan.com/yaoyiyao/queenActivity.html&comCode=1';
                    } else {

                        if (CYutils.isAndroid()) {
                            Android.login('location.reload', 'location.reload');
                        } else if (CYutils.isIOS()) {
                            // mui.toast('isIOS');
                            bridge.send({
                                Foo: "login",
                                "loginResultFunction": 'location.reload'
                            });
                        } else {
                            CYutils.dialog('请使用微信或兴隆大院App访问', {
                                onConfirm: function () {}
                            });
                        }
                    }
                }
            });
            //
            //     }
            // });

            // mui.toast(data.Msg+'121212');
        } else {
            mui.toast(data.Msg);
        }
    });
}
$(document).ready(function () {
    shakeStart();
    $(".mb-bg").hide();
});

// CYutils.ajax(webApp.shake_allLogData, {type:'post'}).then(function(data){
webApp.post(webApp.shake_allLogData, {}, function (data) {
    console.log(data);
    var listitem = data.data;
    if (data.Error == 0 && listitem) {
        var html = ''
        if (listitem.length < 1) {
            $('.news_li').html('敬请期待');
            return;
        }
        for (var i in listitem) {
            var listitem_name = listitem[i].nickname;
            if (listitem_name == '' || listitem_name == undefined) {
                listitem_name = '王**'
            } else {
                // listitem_name=listitem_name.replace(listitem_name.substr(1,2), "**")
                listitem_name = $.trim(listitem_name).replace(/[^.|.]/g, function ($1, $2) {
                    return $2 == 1 || $2 == 2 ? '*' : $1
                })
            }
            html += '<li><a href="#" >' + listitem_name + '  获得' + listitem[i].title + '</a></li>'
        }
        console.log(html);
        $('.news_li').html(html);
        $('.swap').html($('.news_li').html());
        news_lix = $('.news_li');
        news_liy = $('.swap');
        news_lih = $('.news_li li').length * 19; //19为每个li的高度
        setTimeout(b, 3000); //滚动间隔时间 现在是3秒

    }
});

//摇一摇初始化设置------------------
// var shakeFlag = true;  
var SHAKE_THRESHOLD = 4000;
var last_update = 0;
var start = true;
var x = y = z = last_x = last_y = last_z = 0;
var count_last = 0;
// var text_a = 0;
if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
    alert('您的浏览器不支持此功能');
};
//摇一摇初始化设置------------------
//摇一摇事件--------------
function deviceMotionHandler(eventData) {
    if (canUseShake && distanceCanUseShake && otherCanUseShake) {
        var acceleration = eventData.accelerationIncludingGravity;
        var curTime = new Date().getTime();
        if ((curTime - last_update) > 100) {
            var diffTime = curTime - last_update;
            last_update = curTime;
            x = acceleration.x;
            y = acceleration.y;
            z = acceleration.z;
            var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 20000;
            if (speed > SHAKE_THRESHOLD && start) {
                count_last++;
                if (count_last % 2 == 0) {
                    start = false;
                    count_last = 0;
                    setTimeout(
                        function () {
                            if (canplay == true) {
                                c_audio.play();
                            };
                            if (shuju.id > 0) {
                                jQuery.ajax({
                                    url: webApp.sendRequest,
                                    dataType: 'jsonp',
                                    data: {
                                        "id": shuju.id
                                    },
                                    jsonp: 'callback',
                                    success: function (data) {
                                        if (canplay == true) {
                                            c_audio2.play();
                                        };
                                        console.log(data);
                                        if (data.Error == 0) {
                                            // text_a++;
                                            // $('#test').val(text_a +'=='+ start + '=='+count_last);
                                            // var _h = template('yyySuccessTemplate',{data: data.data});
                                            // document.getElementById('scccessshow').innerHTML = _h;
                                            get_shuju = data.data;
                                            var i = data.data.prize_key;
                                            // jQuery('#success').children('div').append(imageObj[i]);
                                            // jQuery('#success').children('div').children('img').bind('tap',function(){
                                            //     jQuery('#success').hide();
                                            //     jQuery('#mui-backdrop').hide();
                                            //     jQuery('#butt_shi').hide();
                                            //     jQuery('#butt_xu').hide();
                                            //     start = true;
                                            //     jQuery('#success').children('div').empty(imageObj[i]);
                                            // })
                                            jQuery('#scccessshowMoney').html(data.data.title);
                                            jQuery('#scccessshowDes').html(data.data.title);
                                            jQuery('#jxyyy').bind('tap', function () {
                                                jQuery('#success').hide();
                                                jQuery('#mui-backdrop').hide();
                                                shakeStart();
                                                start = true;
                                                // jQuery('#success').children('div').empty(imageObj[i]);
                                            })
                                            // jQuery('#ckkjb').bind('tap',function(){
                                            //     jQuery('#success').hide();
                                            //     jQuery('#mui-backdrop').hide();
                                            //     start = true;
                                            //     window.location.href = 'https://wx52b1c0d4c35f2531.webwx.xinglongdayuan.com/app/member/discountvoucher';
                                            //     // jQuery('#success').children('div').empty(imageObj[i]);
                                            // });
                                            jQuery('#successClose').bind('tap', function () {
                                                jQuery('#success').hide();
                                                jQuery('#mui-backdrop').hide();
                                                shakeStart();
                                                start = true;
                                                // jQuery('#success').children('div').empty(imageObj[i]);
                                            });
                                            jQuery('#mui-backdrop').show();
                                            jQuery('#success').show();
                                        } else if (data.Error == 6001 || data.Error == 6008) { //未中奖弹窗
                                            jQuery('#mui-backdrop').show();
                                            jQuery('#error').show();
                                            jQuery('#error').children('img').bind('tap', function () {
                                                jQuery('#error').hide();
                                                jQuery('#mui-backdrop').hide();
                                                shakeStart();
                                                start = true;
                                            });
                                            jQuery('#jxyyy2').bind('tap', function () {
                                                jQuery('#mui-backdrop').hide();
                                                shakeStart();
                                                jQuery('#error').hide();
                                                start = true;
                                            })

                                            if (jQuery("#testdiv").length == 0) {
                                                jQuery("body").append("<div id='testdiv' style='display:none;color:#ffffff;position:absolute;z-index:500;width:100%;height:auto;background-color:black;left:0;top:0;'></div>");
                                            }

                                            jQuery("#testdiv").html(JSON.stringify(data));

                                        } else if (data.Error == 6002) {
                                            mui.alert(data.Msg, '温馨提示', function () {
                                                window.location.href = 'https://shake.xinglongdayuan.com/queenActivity.html';
                                                start = true;
                                            });
                                        } else if (data.Error == 6003) {
                                            jQuery('#mui-backdrop').show();
                                            jQuery('#error4').show();
                                            jQuery('#error4notimeImg').click(function () {
                                                jQuery('#error4').hide();
                                                jQuery('#mui-backdrop').hide();
                                                start = true;
                                            });
                                        } else if (data.Error == 6004) {
                                            mui.alert(data.Msg, '温馨提示', function () {
                                                location.href = 'https://user.wx.xinglongdayuan.com/jumpurl?acurl=https%3A%2F%2Fwx.shake.xinglongdayuan.com%2Fyaoyiyao%2FqueenActivity.html';
                                            });
                                        } else if (data.Error == 6006) {
                                            jQuery('#mui-backdrop').show();
                                            jQuery('#error3').show();
                                            jQuery('#notimeImg').click(function () {
                                                jQuery('#error3').hide();
                                                jQuery('#mui-backdrop').hide();
                                                start = true;
                                            });
                                            // jQuery('#error3').children('img').bind('tap',function(){
                                            //     jQuery('#error3').hide();
                                            //     jQuery('#mui-backdrop').hide();
                                            //     start = true;
                                            // })
                                        } else if (data.Error == 60010) {
                                            mui.alert(data.Msg, function () {

                                            });
                                        }
                                    },
                                    error: function () {
                                        jQuery('#mui-backdrop').show();
                                        jQuery('#error').show();
                                        jQuery('#error').children('img').bind('tap', function () {
                                            jQuery('#error').hide();
                                            jQuery('#mui-backdrop').hide();
                                            shakeStart();
                                            start = true;
                                        })
                                        jQuery('#error2Close').bind('tap', function () {
                                            jQuery('#error').hide();
                                            jQuery('#mui-backdrop').hide();
                                            shakeStart();
                                            start = true;
                                        })
                                    }
                                });

                            } else if(shuju.id != undefined){
                                jQuery('#mui-backdrop').show();
                                jQuery('#error').show();
                                jQuery('#error').children('img').bind('tap', function () {
                                    jQuery('#error').hide();
                                    jQuery('#mui-backdrop').hide();
                                    start = true;
                                })
                                jQuery('#jxyyy2').bind('tap', function () {
                                    jQuery('#success').hide();
                                    jQuery('#mui-backdrop').hide();
                                    shakeStart();
                                    jQuery('#error').hide();
                                    start = true;
                                })
                                jQuery('#error2Close').bind('tap', function () {
                                    jQuery('#error').hide();
                                    jQuery('#mui-backdrop').hide();
                                    start = true;
                                })
                            }else if(shuju.id == undefined){
                                mui.alert('活动已结束', function () {

                                });
                            }
                        }, Math.random() * 200 + 1500);

                    //震动
                    var supportsVibrate = "vibrate" in navigator;
                    if (supportsVibrate) {
                        navigator.vibrate(500);
                    }
                }

            }
            last_x = x;
            last_y = y;
            last_z = z;
        };
    }

};
// 点击模拟摇一摇
var yy_c = true;
var eventData = {
    'accelerationIncludingGravity': {
        x: '',
        y: '',
        z: ''
    }
};
jQuery('#zhongjiang').bind('tap', function () {
    if (yy_c == true) {
        eventData = {
            'accelerationIncludingGravity': {
                x: 100,
                y: 100,
                z: 100
            }
        };
        yy_c = false;
    } else {
        eventData = {
            'accelerationIncludingGravity': {
                x: 200,
                y: 200,
                z: 200
            }
        };
        yy_c = true;
    }
    deviceMotionHandler(eventData);

});
jQuery('#tickedList').on('tap', '.ticket-right', function (event) {
    var _index = this.dataset.id;
    if (tickedList[_index]['type'] == 2) {
        window.location.href = 'https://wx52b1c0d4c35f2531.webwx.xinglongdayuan.com/app/member/discountvoucher#discountCouponDetail?coupon_id=' + tickedList[_index]['coupon_log_id'];
    } else if (tickedList[_index]['type'] == 1) {
        if (tickedList[_index]['coupon_id'] == '4737' || tickedList[_index]['coupon_id'] == '4751') {
            window.location.href = 'https://wx52b1c0d4c35f2531.webwx.xinglongdayuan.com/app/newhipay?/#/index?redirect=payShift&couponLogId=' + tickedList[_index]['couponLogId'];
        } else {
            window.location.href = 'https://wx52b1c0d4c35f2531.webwx.xinglongdayuan.com/app/eshop/goodslist?couponId=' + tickedList[_index]['coupon_id'];
        }
    }

});

function b() {
    t = parseInt(news_lix.css('top'));
    news_liy.css('top', '19px');
    news_lix.animate({
        top: t - 19 + 'px'
    }, 'slow'); //19为每个li的高度
    if (Math.abs(t) == news_lih - 19) { //19为每个li的高度
        news_liy.animate({
            top: '0px'
        }, 'slow');
        news_liz = news_lix;
        news_lix = news_liy;
        news_liy = news_liz;
    }
    setTimeout(b, 3000); //滚动间隔时间 现在是3秒
}
//播放-暂停
$("#audioBtn").click(function () {
    //	alert("Alert text");
    if (canplay == false) {
        c_audio3.play();
        $("#audioBtn").removeClass("mscBtn_stop").addClass("mscBtn");
        canplay = true;
    } else {
        c_audio3.pause();
        $("#audioBtn").removeClass("mscBtn").addClass("mscBtn_stop");
        canplay = false;
    }
});

function closeAudio() {
    c_audio3.pause();
};
// 点击模拟摇一摇
//摇一摇事件--------------

function realod() {
    var {
        search,
        href
    } = window.location;
    href = href.replace(/&?t_reload=(\d+)/g, '')
    window.location.href = href + (search ? '&' : '?') + "t_reload=" + new Date().getTime()
}

document.addEventListener('visibilitychange', function () {
    if (document.visibilityState == 'visible') {
        // window.location.href = location.href + '?time=' + ((new Date()).getTime());
        if (timestamp <= startTime + interval * 60 * (number - 1) + 60) {
            realod();
        }
    }
})

// 倒计时
timer = function () {
    var minute = 0,
        second = 0; //时间默认值        
    if (intDiff > 0) {
        day = Math.floor(intDiff / (60 * 60 * 24));
        hour = Math.floor(intDiff / (60 * 60)) - (day * 24);
        minute = Math.floor(intDiff / 60) - (hour * 60);
        second = Math.floor(intDiff) - (minute * 60) - (hour * 3600);
    }
    if (minute <= 9) minute = '0' + minute;
    if (second <= 9) second = '0' + second;
    // $('#day_show').html(day+"天");
    // $('#hour_show').html('<s id="h"></s>'+hour+'时');
    $('#hour_show').html('<s></s>' + hour + '时');
    $('#minute_show').html('<s></s>' + minute + '分');
    $('#second_show').html('<s></s>' + second + '秒');
    // $('#juli').html('距离下一轮摇奖还剩：');
    intDiff--;

}
timer0 = function () {
    var minute = 0,
        second = 0; //时间默认值        
    if (intDiff1 > 0) {
        day = Math.floor(intDiff1 / (60 * 60 * 24));
        hour = Math.floor(intDiff1 / (60 * 60)) - (day * 24);
        minute = Math.floor(intDiff1 / 60) - (hour * 60);
        second = Math.floor(intDiff1) - (minute * 60) - (hour * 3600);
    }
    if (minute <= 9) minute = '0' + minute;
    if (second <= 9) second = '0' + second;
    // $('#day_show').html(day+"天");
    // $('#hour_show').html('<s id="h"></s>'+hour+'时');
    $('#hour_show').html('<s></s>' + hour + '时');
    $('#minute_show').html('<s></s>' + minute + '分');
    $('#second_show').html('<s></s>' + second + '秒');
    // $('#juli').html('本轮摇奖时间剩余：');
    intDiff1--;

}

// 获取当前时间
function getNow(s) {
    return s < 10 ? '0' + s : s;
}
webApp.post(webApp.getTime, {}, function (data) {
    console.log(data);
    if (data.Error == 0) {
        console.log(data.time);
        timestamp = data.time;
        // 页面刷新判断当前times
        if (startTime < timestamp) {
            times = parseInt((timestamp - startTime) / (interval * 60)) + 1;
        } else {
            times = 1;
        }
        if (data.subscribe == 1) {
            otherCanUseShake = true;
        } else {
            otherCanUseShake = false;
            mui.alert('请先关注兴隆大院公众号', function () {
                location.href = 'https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIxNjEzMDcxNQ==&scene=126&bizpsid=0#wechat_redirect';
            });
        }
        clearInterval(dTimer1);
        dTimer1 = setInterval(dTime1, 1000);
    }
});

var dTimer1 = null;

function dTime1() {
    timestamp++
    //活动未开始等待时间
    if (timestamp < startTime) {
        intDiff = parseInt(startTime - timestamp);
        clearInterval(sTimer);
        sTimer = setInterval(timer(), 1000);
    } else {
        if (timestamp >= startTime && timestamp < startTime + interval * 60 * number) {
            //4分钟等待
            if (timestamp < startTime + (times - 1) * interval * 60 + 60 * interval && startTime + (times - 1) * interval * 60 + 60 < timestamp) {
                $("#cjju-time").text("距离下轮摇奖还剩");
                intDiff = parseInt(startTime + (times - 1) * interval * 60 + 60 * interval - timestamp);
                clearInterval(sTimer);
                sTimer = setInterval(timer(), 1000);
                // getList();
                // 亮屏后刷新数据
                if (times == number) {
                    clearInterval(dTime1);
                    $(".jihui").html("");
                    $(".jihui").text("本次活动结束，谢谢参与！");
                }
            }
            //1分钟摇奖时间
            if (timestamp < startTime + (times - 1) * interval * 60 + 60) {
                $("#cjju-time").text("本轮摇奖还剩");
                intDiff1 = parseInt(startTime + (times - 1) * interval * 60 + 60 - timestamp);
                clearInterval(sTimer0);
                sTimer0 = setInterval(timer0(), 1000);
                // getData();
            }
            //到时间进行下一轮
            if (timestamp == startTime + times * interval * 60) {
                // idmum = null;
                times++
            }
        } else {
            clearInterval(dTime1);
            $(".jihui").html("");
            $(".jihui").text("本次活动结束，谢谢参与！");
        }
    }

}

wx.ready(function () {
    // wx.getLocation({
    //     type: 'wgs84',
    //     success: function (res) {
    //         //获取到地理位置拉数据
    //         // webApp.OrderUrl.latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
    //         // webApp.OrderUrl.longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
    //         // var speed = res.speed; // 速度，以米/每秒计
    //         // var accuracy = res.accuracy; // 位置精度
    //         console.log(res.latitude + '--' + res.longitude);
    //         // mui.alert('', res.latitude + '--' + res.longitude, function () {

    //         // });
    //         Latitude = res.latitude;
    //         Longitude = res.longitude;
    //         distanceByLnglat(Latitude, Longitude, 41.79793930053711, 123.44953918457031);
    //         // mui.alert(res.latitude + '--' + res.longitude, '获取到地理位置', function () {

    //         // });
    //     },
    //     cancel: function (res) {
    //         //用户拒绝拉数据
    //     },
    //     fail: function (res) {
    //         //调用失败时拉数据
    //         //被拒绝再次拉去请求
    //         // wx.authorize({ scope: "scope.userLocation" })
    //         mui.alert('请先去设置中开启微信位置权限,否则您将无法参加活动', function () {

    //         });
    //     }
    // })
})

function distanceByLnglat(la1, lo1, la2, lo2) {

    var La1 = la1 * Math.PI / 180.0;

    var La2 = la2 * Math.PI / 180.0;

    var La3 = La1 - La2;

    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;

    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));

    s = s * 6378.137; //地球半径

    s = Math.round(s * 10000) / 10000;

    if(s <= 0.2){
    distanceCanUseShake = true;
    }else{
        distanceCanUseShake = false;
        // mui.alert('请到活动现场参加活动' , function () {

        // });
        jQuery('#mui-backdrop').show();
        jQuery('#distance').show();

    }

    // console.log("计算结果",s)

}

function Rad(d) {
    return d * Math.PI / 180.0;
}